import client from '@lib/client'
import { Button, Form, Input, Modal, message } from 'antd'
import React, { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'

const { Search } = Input

export interface ICreateUserButtonProps {
  refresh: () => void
}

export default function CreateUserButton(props: ICreateUserButtonProps) {
  const { t } = useTranslation()

  const { refresh } = props

  const [visible, setVisible] = useState(false)
  const [isPosting, setIsPosting] = useState(false)

  const handleOpen = useCallback(() => {
    setVisible(true)
  }, [])

  const handleClose = useCallback(() => {
    setVisible(false)
    setIsPosting(false)
  }, [])

  const handleFinish = useCallback(async (values) => {
    try {
      setIsPosting(true)
      const r = await client.getInstance().createUser({
        user_id: values.userId,
        name: values.name,
      })
      if (r.status == 200) {
        message.success('Success')
        setVisible(false)
        refresh()
      }
    } finally {
      setIsPosting(false)
    }
  }, [])

  return (
    <>
      <Button type="primary" onClick={handleOpen}>
        {t('user_list.button.create_user')}
      </Button>
      <Modal
        title={t('user_list.modal.create_user.title')}
        visible={visible}
        destroyOnClose
        onCancel={handleClose}
        width={600}
        footer={null}
      >
        {/* <DebounceSelect />
        <Divider /> */}
        <Form onFinish={handleFinish}>
          <Form.Item
            name="userId"
            rules={[{ required: true }]}
            label={t('user_list.modal.create_user.form.user_id')}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 14 }}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="name"
            rules={[{ required: true }]}
            label={t('user_list.modal.create_user.form.name')}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 14 }}
          >
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ span: 14, offset: 4 }}>
            <Button type="primary" htmlType="submit" loading={isPosting}>
              {t('user_list.modal.create_user.submit')}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
